﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Configuration;
using VSS_AHT.Helpers;
using VSSAHT.DataAccess;
using VSSAHT.Transfer;
using System.Xml.Serialization;
using System.IO;
using VSS_AHT.Properties;
using System.Diagnostics;

namespace VSS_AHT.Forms
{
    public partial class FormLogin : BaseForm
    {
        public FormLogin()
        {
            InitializeComponent();

            svc.AddService(typeof(IRoleDataAccess), new RoleDataAccess());
            svc.AddService(typeof(IUserDataAccess), new UserDataAccess());
        }

        protected override void OnLoadData()
        {
            // Load connection type
            this.cboConnectionType.Properties.Items.Add("Kết nối mặc định");
            this.cboConnectionType.Properties.Items.Add("Thay đổi kết nối");
            this.cboConnectionType.SelectedIndex = 0;

            // Load Remember File
            this.LoadRemeberFile();

            base.OnLoadData();
        }

        private void LoadRemeberFile()
        {
            try
            {
                // Check is remeber
                if (File.Exists(Common.RememberPath))
                {
                    RememberDTO remember = Serializer<RememberDTO>.Deserialize(Common.RememberPath);

                    this.chkRemember.Checked = true;
                    this.txtUsername.Text = remember.Username;
                    this.txtPassword.Text = remember.PasswordEncrypt;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        protected override void OnEvents()
        {
            this.cboConnectionType.SelectedIndexChanged += new EventHandler(cboConnectionType_SelectedIndexChanged);
            this.rdoConnectionType.SelectedIndexChanged += new EventHandler(rdoConnectionType_SelectedIndexChanged);

            this.btnSetConnection.Click += new EventHandler(btnSetConnection_Click);
            this.btnLogon.Click += new EventHandler(delegate
            {
                if (this.Authorization())
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    Common.ShowAlert("Tài khoản đăng nhập không hợp lệ!");
                }
            });
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });

            base.OnEvents();
        }

        private bool Authorization()
        {
            bool result = false;

            string username = this.txtUsername.Text;
            string password = this.txtPassword.Text;

            if (String.Compare(username, Common.defaultUsername, true) == 0 &&
                String.Compare(this.txtPassword.Text, Common.defaultPassword, true) == 0)
            {
                // user system administrators
                Common.UserLogin = new UserDTO();
                Common.UserLogin.Username = Common.defaultUsername;
                Common.UserLogin.RoleID = Guid.Empty;

                Demo();

                result = true;
            }
            else
            {
                // authorize login
                IUserDataAccess daUser = (svc.GetService(typeof(IUserDataAccess)) as IUserDataAccess);
                Common.UserLogin = new UserDTO();
                Common.UserLogin.Username = username;
                Common.UserLogin.PasswordEncrypt = Security.Encrypt(password);
                result = daUser.Authentication(ref Common.UserLogin);
            }

            // Process remember
            if (this.chkRemember.Checked)
            {
                // Check to store remember
                RememberDTO remember = new RememberDTO();
                remember.Username = this.txtUsername.Text;
                remember.PasswordEncrypt = this.txtPassword.Text;

                Serializer<RememberDTO>.Serialize(remember, Common.RememberPath);
            }
            else
            {
                // Uncheck to remove remember
                if (File.Exists(Common.RememberPath))
                    File.Delete(Common.RememberPath);
            }

            return result;
        }

        private void Demo()
        {
            // Demo role
            IRoleDataAccess daRole = (svc.GetService(typeof(IRoleDataAccess)) as IRoleDataAccess);
            var roles = daRole.GetAll();
            if (roles == null || roles.Count == 0)
            {
                RoleDTO role;
                // Admin role
                role = new RoleDTO();
                role.RoleCode = "AD";
                role.RoleName = "Quản trị";
                role.Permitted = new PermissionDTO();
                role.Permitted.ItemPermitted = 63;
                role.Permitted.CustomerPermitted = 63;
                role.Permitted.LocationPermitted = 63;
                role.Permitted.ModelVehiclePermitted = 63;
                role.Permitted.RequireNumberPermitted = 63;
                role.Permitted.ScaleTicketPermitted = 63;
                role.Permitted.UserPermitted = 63;
                role.Permitted.ConfigPermitted = 63;
                role.Permitted.ExportExcelViaRequire = true;
                role.Permitted.ManualScale = true;
                role.Permits = Serializer<PermissionDTO>.SerializeObj(role.Permitted);
                daRole.Add(role);

                // Role 20KG
                role = new RoleDTO();
                role.RoleCode = "20TAN";
                role.RoleName = "Nhóm cân 20 TẤN";
                role.Permitted = new PermissionDTO();
                role.Permitted.ItemPermitted = 0;
                role.Permitted.CustomerPermitted = 0;
                role.Permitted.LocationPermitted = 0;
                role.Permitted.ModelVehiclePermitted = 0;
                role.Permitted.RequireNumberPermitted = 0;
                role.Permitted.ScaleTicketPermitted = 1;
                role.Permitted.UserPermitted = 0;
                role.Permitted.ConfigPermitted = 0;
                role.Permitted.ExportExcelViaRequire = false;
                role.Permitted.ManualScale = false;
                role.Permits = Serializer<PermissionDTO>.SerializeObj(role.Permitted);
                daRole.Add(role);

                // Role 80KG
                role = new RoleDTO();
                role.RoleCode = "80TAN";
                role.RoleName = "Nhóm cân 80 TẤN";
                role.Permitted = new PermissionDTO();
                role.Permitted.ItemPermitted = 0;
                role.Permitted.CustomerPermitted = 0;
                role.Permitted.LocationPermitted = 0;
                role.Permitted.ModelVehiclePermitted = 0;
                role.Permitted.RequireNumberPermitted = 0;
                role.Permitted.ScaleTicketPermitted = 1;
                role.Permitted.UserPermitted = 0;
                role.Permitted.ConfigPermitted = 0;
                role.Permitted.ExportExcelViaRequire = true;
                role.Permitted.ManualScale = false;
                role.Permits = Serializer<PermissionDTO>.SerializeObj(role.Permitted);
                daRole.Add(role);
            }

            // Test user
            IUserDataAccess daUser = (svc.GetService(typeof(IUserDataAccess)) as IUserDataAccess);
            var users = daUser.GetAll();
            if (users == null || users.Count == 0)
            {
                UserDTO user = new UserDTO();
                user.Username = "admin";
                user.PasswordEncrypt = Security.Encrypt("admin");
                RoleDTO role = daRole.GetByCode("AD");
                user.RoleID = role.RoleID;

                daUser.Add(user);


                user = new UserDTO();
                user.Username = "user1";
                user.PasswordEncrypt = Security.Encrypt("123");
                role = daRole.GetByCode("20TAN");
                user.RoleID = role.RoleID;

                daUser.Add(user);

                user = new UserDTO();
                user.Username = "user2";
                user.PasswordEncrypt = Security.Encrypt("456");
                role = daRole.GetByCode("80TAN");
                user.RoleID = role.RoleID;

                daUser.Add(user);
            }
        }

        protected void rdoConnectionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.groupControl3.Enabled = !this.rdoConnectionType.EditValue.Equals(true);
        }

        protected void btnSetConnection_Click(object sender, EventArgs e)
        {
            bool result = false;
            if (this.rdoConnectionType.EditValue.Equals(true))
                result = ConfigProcessing.CreateConfigurationFile(this.txtServer.Text, this.txtDatabase.Text);
            else
                result = ConfigProcessing.CreateConfigurationFile(this.txtServer.Text, this.txtDatabase.Text, this.txtSQLUserID.Text, this.txtSQLPassword.Text);
            if (result)
            {
                MessageBox.Show("Lưu cấu hình thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.cboConnectionType.SelectedIndex = 0;
            }
            else
                MessageBox.Show("Lưu cấu hình không thành công!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        protected void cboConnectionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.cboConnectionType.SelectedIndex)
            {
                case 0: // Default connectionString
                    this.Height = 248;
                    break;
                case 1: // Change connectionString
                    this.Height = 483;
                    string server = String.Empty,
                        database = String.Empty,
                        username = String.Empty,
                        password = String.Empty;
                    //bool local = false;

                    // Hide load two way
                    //ConfigProcessing.GetConnectionString(ref server, ref database, ref username, ref password, ref local);
                    //this.txtServer.Text = server;
                    //this.txtDatabase.Text = database;
                    //this.txtSQLUserID.Text = username;
                    //this.txtSQLPassword.Text = password;
                    //this.rdoConnectionType.EditValue = local;

                    break;

            }
        }

        
       

       
    }
}